package com.lxf.ip;

import javax.servlet.http.HttpServletRequest;

public class IPAddress {
	
	/**
	 * 获取访问者ip地址;
	 * 此方法为获取http请求时的访问者ip地址,需要放在web应用项目下
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (null!=ip && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (null!=ip && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			}else {
				return ip;
			}
		}else{
			return request.getRemoteAddr();
		}
	}

}
